import ogre.renderer.OGRE as ogre
from . import mobileobjects.MobileActor



class LightTower:
    
    def __init__(self,iParent, iName, iRange,  iHeight):
        
        print "start init LT 0"
        self.parent = iParent
        self.yaw = 0.0
        self.cycle = 0.0
        print "start init LT"
        self.direction = 3.141592
        self.amplitude = 1.0
        self.name = iName
        self.range = iRange
        print "start init  2"
        self.light=self.parent.world.MainWindow.SceneMgr.createLight(self.name + "_Light1")
        self.light.Type = ogre.Light.LightTypes.LT_SPOTLIGHT
        self.light.DiffuseColour = ogre.ColourValue.Green
        print "init LV : "
        self.FOV=ogre.Degree(45)
        #mParent.ContainingWorld.MainWindow.log("mLight :" + mLight.AttenuationRange + " / " + mLight.AttenuationConstant + " / " + mLight.AttenuationLinear + " / " + mLight.AttenuationQuadric);
        
        self.light.setAttenuation(self.range, 0.0001,0.001, 0.0000004)
        #mParent.ContainingWorld.MainWindow.log("mLight :" + mLight.AttenuationRange + " / " + mLight.AttenuationConstant + " / " + mLight.AttenuationLinear + " / " + mLight.AttenuationQuadric);
        self.light.setSpotlightRange(ogre.Degree(30), self.FOV,1.0)
        
        q=ogre.Quaternion()
        q.FromAngleAxis(ogre.Radian(ogre.Degree(0)), ogre.Vector3.NEGATIVE_UNIT_Z)
        self.light.Direction = q*ogre.Vector3.UNIT_X
        

        self.sceneNode = self.parent.node.createChildSceneNode()
        self.sceneNode.inheritScale = False
        self.sceneNode.translate(1.0, iHeight, 0)
        self.sceneNode.attachObject(self.light)
        print "init LV OK"
    
    def setDirAmpl(self, iDest):
        
            minLength = 20.0
            
            iDest.y=self.parent.Position.y
            src = self.parent.Orientation * ogre.Vector3.UNIT_X
            iDiff= iDest - self.parent.Position
            length = iDiff.Length
            if length < 10.0 : length=10.0
            
            dp=src.DotProduct(iDiff)
            right = src.CrossProduct(ogre.Vector3.NEGATIVE_UNIT_Y)

            th = ogre.Math.ACos(dp / length).ValueRadians

            if right.DotProduct(iDiff)<0 :
                self.direction =   -th
            else :
                self.direction =   -th

            self.amplitude = 3.14159/ (length*length) * minLength*minLength
            
    def doTimer(self,dt):
    
        self.cycle = self.cycle+dt
        self.cycle = self.cycle%(ogre.Math.PI * 2)
        
        self.yaw = self.direction + ogre.Math.Cos(self.cycle) * self.amplitude

        
        q = ogre.Quaternion(self.yaw, ogre.Vector3.UNIT_Y)
        self.sceneNode.Orientation = q
        
    def __del__(self):
        self.parent.ContainingWorld.MainWindow.SceneMgr.DestroyLight(self.light)
        self.light.Dispose()
        self.parent.ContainingWorld.MainWindow.SceneMgr.DestroySceneNode(self.sceneNode.Name)
        self.sceneNode.Dispose()